// content.js 
// 页面注册
chrome.runtime.sendMessage({
  action: 'registerPage',
  url: window.location.href
});

// 页面卸载时取消注册
window.addEventListener('beforeunload', () => {
  try {
    // 检查扩展上下文是否有效
    if (chrome.runtime?.id) {
      chrome.runtime.sendMessage({
        action: 'unregisterPage'
      });
    }
  } catch (error) {
    //console.warn('扩展上下文已失效，无法发送消息:', error);
  }

});

// 监听来自后台的HTML请求
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  //console.log("后台返回：",message);
  if (message.action === 'fetchHtml') {
    // 获取页面HTML
    let html = '';
    if (message.targetCss) {
      html = document.documentElement.querySelector(message.targetCss).innerHTML;
    } else {
      html = document.documentElement.outerHTML;
    }
    sendResponse({ html });// 将HTML内容返回给后台
    return true;
  }
  if (message.action === 'htmlResponse') {
    window.postMessage({
      type: 'htmlResponse',
      html: message?.html,
      requestId: message?.requestId,
    }, '*');
    return true;
  }
});

// 监听来自页面的消息
window.addEventListener('message', (event) => {
  if (event.source === window && event.data.type === 'htmlRequest') {
    console.log(`[CONTENT] 收到页面请求，requestId: ${event.data.requestId}`);

    // 转发请求到后台
    chrome.runtime.sendMessage({
      action: 'requestHtml',
      requestId: event.data.requestId,
      targetUrl: event.data.targetUrl,
      targetCss: event.data.targetCss
    }, (response) => {
      // console.log(`[CONTENT] 返回页面请求，requestId: ${event.data.requestId}`);
      // // 将响应发送回页面
      // window.postMessage({
      //   type: 'htmlResponse',
      //   requestId: event.data.requestId,
      //   html: response?.html,
      //   error: response?.error
      // }, '*');
    });
  }
});